package io.github.codelifeleno.jdbrelease.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class DataUtil {

    private static final Logger log = LoggerFactory.getLogger(DataUtil.class);
    static Map<Class<?>, Supplier<?>> dateValues = Map.of(
            java.sql.Date.class, () -> new java.sql.Date(System.currentTimeMillis()),
            java.util.Date.class, () -> new java.util.Date(System.currentTimeMillis()),
            java.time.LocalDate.class, LocalDate::now,
            java.time.LocalDateTime.class, LocalDateTime::now,
            java.time.LocalTime.class, LocalTime::now
    );
    static Map<Class<?>, Supplier<?>> simpleValues = Map.of(
            String.class, () -> "",
            Integer.class, () -> 0,
            Double.class, () -> 0.0,
            Float.class, () -> 0.0F,
            Boolean.class, () -> false,
            Long.class, () -> 0L,
            BigDecimal.class, () -> BigDecimal.ZERO
    );
    static Map<Class<?>, Supplier<?>> defaultValues = new HashMap<>(simpleValues);

    static {
        defaultValues.putAll(dateValues);
    }

    public static <T> Object getDataDefault(Object object, Class<T> clazz) {
        if (object == null) {
            return getDefaultValue(clazz);
        } else {
            // 如果对象的类型与目标类型一致，直接返回
            if (clazz.isInstance(object)) {
                return object;
            } else {
                // 如果类型不一致，也返回默认值
                return getDefaultValue(clazz);
            }
        }
    }

    private static <T> Object getDefaultValue(Class<T> clazz) {


        Supplier<?> defaultValueSupplier = defaultValues.get(clazz);
        if (defaultValueSupplier != null) {
            return defaultValueSupplier.get();
        } else {
            // 如果没有找到默认值的类型，尝试通过反射创建实例
            try {
                return clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException("Failed to create instance for class: " + clazz.getName(), e);
            }
        }
    }

    // 示例使用
    public static void main(String[] args) {
        // 示例1：传入null，返回默认值
        System.out.println(getDataDefault(null, String.class)); // ""
        System.out.println(getDataDefault(null, Integer.class)); // 0

        // 示例2：传入非null对象，类型匹配
        System.out.println(getDataDefault(123, Integer.class)); // 123
        System.out.println(getDataDefault("Hello", String.class)); // "Hello"

        // 示例3：传入非null对象，类型不匹配
        System.out.println(getDataDefault(123, String.class)); // ""
        System.out.println(getDataDefault("Hello", Integer.class)); // 0
    }
}
